package com.norra.base.api

import android.util.Log
import com.norra.base.BuildConfig
import com.norra.base.utils.Logger
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okio.Buffer
import java.io.IOException

/**
 * Created by Charliu on 2017/4/24.
 * 打印http日志
 */

internal class LogInterceptor : Interceptor {
    private val jsonType = "json"
    private val htmlType = "html"
    private val xmlType = "xml"

    private val TAG = "WEB-API"

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        if (BuildConfig.DEBUG) {
            printRequestLog(request)
        }
        val response = chain.proceed(request)
        if (BuildConfig.DEBUG) {
            printResponseLog(response)
        }
        return response
    }

    @Throws(IOException::class)
    private fun printResponseLog(response: Response) {
        val print = StringBuilder()
        print.append("Response，URL=")
        print.append(response.request().url())
        val requestBodyString = getRequestBodyString(response.request())
        if (requestBodyString != null) {
            print.append("?$requestBodyString")
        }

        if (response.body() != null) {
            val mediaType = response.body()!!.contentType()
            if (mediaType != null) {
                print.append(", mediaType=")
                print.append(mediaType.subtype())
                val contentSubType = mediaType.subtype()
                if (jsonType == contentSubType || htmlType == contentSubType || xmlType == contentSubType) {
                    val responseBody = response.peekBody((1024 * 1024).toLong())
                    print.append(",Response=")
                    print.append(responseBody.string())
                }
            }
        }
        Logger.d(TAG, print.toString())
    }

    private fun printRequestLog(request: Request) {
        if ("POST" == request.method()) {
            val requestBodyString = getRequestBodyString(request)
            if (requestBodyString != null) {
                Log.d(TAG, "Request, " + request.method() + " url:" + request.url().url().toString() + ", headers=" + request.headers() + ", body=" + requestBodyString)
            } else {
                Log.d(TAG, "Request, " + request.method() + " url:" + request.url().url().toString())
            }
        } else {
            Log.d(TAG, "Request, " + request.method() + "  url:" + request.url().url().toString())
        }
    }

    private fun getRequestBodyString(request: Request): String? {
        val requestBody = request.body()
        if (requestBody != null) {
            val buffer = Buffer()
            try {
                requestBody.writeTo(buffer)
            } catch (e: IOException) {
                e.printStackTrace()
            }
            return buffer.readUtf8()
        }
        return null
    }
}
